<template>
  <div class="roles">
    <el-card>
      <el-row :gutter="20">
        <el-col :span="2">
          <el-button type="primary" @click="addRolesFormVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table
        :data="rolesList"
        max-height="600px"
        border
        style="width: 100%; margin: 10px 0"
      >
        <!-- 下拉列表 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['row_border_bottom', index == 0 ? 'row_border_top' : '']"
              v-for="(item, index) in scope.row.children"
              :key="item.id"
            >
              <el-col class="col-center" :span="6">
                <el-tag @close="GrantClose(scope.row, item.id)" closable>
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col class="col-right" :span="18">
                <el-row
                  :class="index2 != 0 ? 'row_border_top' : ''"
                  v-for="(item2, index2) in item.children"
                  :key="item2.id"
                >
                  <el-col class="col-center" :span="6">
                    <el-tag
                      @close="GrantClose(scope.row, item2.id)"
                      type="success"
                      closable
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-col>
                      <el-tag
                        type="warning"
                        closable
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        @close="GrantClose(scope.row, item3.id)"
                        >{{ item3.authName }}</el-tag
                      >
                    </el-col>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-row
              v-if="scope.row.children.length == 0"
              style="text-align: center"
              ><el-col :span="24">该角色暂无权限</el-col></el-row
            >
          </template>
        </el-table-column>
        <!-- 头部标题 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              @click="showEditRoles(scope.row)"
              size="mini"
              type="primary"
              icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button
              @click="delRoles(scope.row)"
              size="mini"
              type="danger"
              icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              @click="showGrant(scope.row)"
              size="mini"
              type="warning"
              icon="el-icon-s-tools"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addRolesFormVisible">
      <el-form ref="addRolesFormData" :model="addRolesFormData" :rules="rules">
        <el-form-item
          prop="roleName"
          label="角色名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="addRolesFormData.roleName"></el-input>
        </el-form-item>
        <el-form-item
          prop="roleDesc"
          label="角色描述"
          :label-width="formLabelWidth"
        >
          <el-input v-model="addRolesFormData.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRolesFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesForm('addRolesFormData')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog title="编辑角色" :visible.sync="editRolesFormVisible">
      <el-form
        ref="editRolesFormData"
        :model="editRolesFormData"
        :rules="rules"
      >
        <el-form-item
          prop="roleName"
          label="角色名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editRolesFormData.roleName"></el-input>
        </el-form-item>
        <el-form-item
          prop="roleDesc"
          label="角色描述"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editRolesFormData.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editRolesFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesForm()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="setGrantFormVisible">
      <el-tree
        ref="tree"
        :show-checkbox="true"
        node-key="id"
        default-expand-all
        :data="grantList"
        :props="grantProps"
        :default-checked-keys="selectList"
      ></el-tree>

      <div slot="footer" class="dialog-footer">
        <el-button @click="setGrantFormVisible = false">取 消</el-button>
        <el-button @click="editGrant" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoles,
  getAddRoles,
  getDelRoles,
  getEditRoles,
  getRights,
  getEditRights,
  getDelRights,
} from "@/api/index";
export default {
  data() {
    return {
      rolesList: [],
      grantList: [],
      roleId: "",
      selectList: [],
      grantProps: {
        label: "authName",
        children: "children",
      },
      addRolesFormVisible: false,
      editRolesFormVisible: false,
      setGrantFormVisible: false,
      formLabelWidth: "120px",
      addRolesFormData: {
        roleDesc: "",
        roleName: "",
      },
      editRolesFormData: {
        roleDesc: "",
        roleName: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getRolesForm();
  },
  methods: {
    //移除权限
    async GrantClose(row, rightId) {
      let res = await this.$confirm("此操作将删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (!res) return this.$message("取消删除");
      let {
        data,
        meta: { msg, status },
      } = await getDelRights({ roleId: row.id, rightId });
      status == 200 ? this.$message.success(msg) : this.$message.warning(msg);
      if (status != 200) return this.getRolesForm();
      row.children = data;
    },
    // 分配权限
    async editGrant() {
      let rids = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys(),
      ].join(",");
      let {
        meta: { msg, status },
      } = await getEditRights({ roleId: this.roleId, rids });
      status == 200 ? this.$message.success(msg) : this.$message.warning(msg);
      this.setGrantFormVisible = false;
      this.getRolesForm();
    },
    //显示授权框
    async showGrant(form) {
      let {
        data,
        meta: { msg, status },
      } = await getRights({ type: "tree" });
      if (status != 200) return this.$message.warning(msg);
      this.grantList = data;
      this.selectList = [];
      this.selectIdList(form);
      this.roleId = form.id;
      this.setGrantFormVisible = true;
    },
    // 获取角色权限id
    selectIdList(arr) {
      arr.children.forEach((item) => {
        if (!item.hasOwnProperty("children"))
          return this.selectList.push(item.id);
        this.selectIdList(item);
      });
    },
    // 编辑角色
    async editRolesForm() {
      let {
        meta: { msg, status },
      } = await getEditRoles(this.editRolesFormData);
      console.log(status, msg);
      status == 200
        ? this.$message.success("更新成功")
        : this.$message.warning(msg);
      this.getRolesForm();
      this.editRolesFormVisible = false;
    },
    //展示编辑角色框
    showEditRoles({ id, roleDesc, roleName }) {
      this.editRolesFormData.id = id;
      this.editRolesFormData.roleDesc = roleDesc;
      this.editRolesFormData.roleName = roleName;
      this.editRolesFormVisible = true;
    },
    //删除角色
    async delRoles(form) {
      let res = await this.$confirm("此操作将删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (!res) return this.$message("取消删除");
      let {
        meta: { msg, status },
      } = await getDelRoles(form.id);
      status == 200 ? this.$message.success(msg) : this.$message.warning(msg);
      this.getRolesForm();
    },
    //添加角色
    async addRolesForm(form) {
      try {
        let success = await this.$refs[form].validate();
        if (!success) return false;
        let {
          meta: { msg, status },
        } = await getAddRoles(this.addRolesFormData);
        status == 201 ? this.$message.success(msg) : this.$message.warning(msg);
        this.getRolesForm();
        for (let item in this.addRolesFormData) {
          this.addRolesFormData[item] = "";
        }
        this.addRolesFormVisible = false;
      } catch (error) {
        console.log(error);
      }
    },
    //获取角色数据
    async getRolesForm() {
      let {
        data,
        meta: { msg, status },
      } = await getRoles();
      if (status != 200) return this.$message.warning(msg);
      this.rolesList = data;
    },
  },
};
</script>
<style lang="less" scoped>
.roles {
  .down-box {
    margin: 20px;
  }
  .el-row {
    display: flex;
    align-items: center;
    .col-center {
      text-align: center;
    }
    .col-right {
      border-left: 1px solid #efefef;
      .el-row {
        padding: 10px 0;
      }
      .el-col:last-child {
        .el-tag {
          margin: 5px 10px 5px 0;
        }
      }
    }
  }
  .row_border_top {
    border-top: 1px solid #efefef;
  }
  .row_border_bottom {
    border-bottom: 1px solid #efefef;
  }
}
</style>